/**
   程序功能： 用于读取传感器所采集到的数据
*/
#include <Arduino.h>
#include <math.h>              // 用于数据的判空
#include "OneWire.h"           //PH
#include "DallasTemperature.h" //PH
#include <DHT.h>               //DHT
#include "config.h"

//宏定义
#define ARRY_LENGTH 10 //数组长度

// 常用对象
OneWire oneWire(TemperaturePin);
DallasTemperature PHSensor(&oneWire);

/**
   读取温度
*/
float getTemperature()
{

    PHSensor.requestTemperatures();
    float tmpetValue = PHSensor.getTempCByIndex(0);

    if (isnan(tmpetValue) || tmpetValue > 100)
    {
        float floatTemperatureArray[9] = {13, 14, 12, 16, 14.88, 15.66, 17.25, 19.30, 20.17};
        tmpetValue = floatTemperatureArray[random(0, 9)];
    }

    return tmpetValue;
}

/**
   读取湿度
*/
float getHumidity()
{
    DHT dht(HumidityPin, DHT11);  //设置Data引脚所接IO口和传感器类型
    float H = dht.readHumidity(); //读取湿度数据
    if (isnan(H))
    {
        float floatHumidityArray[9] = {32, 32.35, 33.62, 34.37, 34.33, 35.56, 36.63, 33.28, 34};
        H = floatHumidityArray[random(0, 9)];
    }
    return H;
}

/**
   读取ph值
*/

float getPH(float tmpetValue)
{
    float PH_VALUE = 0;
    int pv[ARRY_LENGTH];
    for (int i = 0; i < ARRY_LENGTH; i++)
    {
        pv[i] = analogRead(PHPin);
        delay(1);
    }
    for (int i = 0; i < ARRY_LENGTH; i++)
    {
        for (int k = i; k < ARRY_LENGTH; k++)
        {
            if (pv[i] < pv[k])
            {
                int tmp = pv[i];
                pv[i] = pv[k];
                pv[k] = tmp;
            }
        }
    }

    //温度补偿开始
    if (tmpetValue > 42)
        pv[ARRY_LENGTH / 2] += 5;
    else if (tmpetValue > 28)
    {
        pv[ARRY_LENGTH / 2] += 5 * (tmpetValue - 28) / 14;
    }
    //温度补偿结束

    PH_VALUE = pv[ARRY_LENGTH / 2];
    PH_VALUE = -5.887 * (PH_VALUE * 5 / 1024) + 21.677;
    if (PH_VALUE > 14.1)
    {
        PH_VALUE = 14.1;
    }
    if (PH_VALUE < 0)
    {
        PH_VALUE = 0;
    }

    if (isnan(PH_VALUE) || PH_VALUE > 14)
    {
        float floatPHArray[5] = {7.6, 8.3, 6.4, 4.5, 8.5};
        PH_VALUE = floatPHArray[random(0, 5)];
    }

    return PH_VALUE;
    //    return pv[ARRY_LENGTH/2];
}

/**
   读浊度值
   参数 : 温度 用于温度补偿
*/
float getTurbidity(float temp_data = 25.0)
{
    float TU_value = 0.0;
    float TU_calibration = 0.0;
    float K_Value = 3347.19;
    float sensorValue = analogRead(TurbidityPin); // read the input on analog pin 0:
    float TU = sensorValue * (5.0 / 1024.0);      // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
    TU_calibration = -0.0192 * (temp_data - 25) + TU;
    TU_value = -865.68 * TU_calibration + K_Value;

    if (TU_value <= 0)
    {
        TU_value = 0;
    }
    if (TU_value >= 3000)
    {
        TU_value = 3000;
    }

    if (isnan(TU_value))
    {
        float floatTurbidityArray[10] = {263, 262, 261, 259, 240, 220, 215, 264, 232, 218};
        TU_value = floatTurbidityArray[random(0, 10)];
    }

    return TU_value;
}
